package com.yck12;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

public class Main2 {

    public static void main(String[] args) throws IOException {
        //建立多人的英文姓名的列表，每个人占用一行，有四列，支持四种英文名称，例如 guo lixin, guo lx, guo lixin, guo lx
        //为每个人拼接一个查询字符串，字符串格式为：AND ((((guo lixin[Author - First]) OR (lixin guo[Author - First])) OR (Guo LX[Author - First])) OR (LX Guo[Author - First])) AND (y_5[Filter])
        List<String> names = Arrays.asList(
                "zhou zhiguang,zhiguang zhou,Zhou ZG,ZG Zhou",
                "zhu min,zhu min,Zhu M,M Zhu",
                "weng jianping,jianping weng,Weng JP,JP Weng",
                "ji linong,linong ji,Li LN,LN Li",
                "guo lixin,lixin guo,Guo LX,LX Guo",
                "yang tao,tao yang,Yang T,T Yang",
                "fu junfen,junfen fu,Fu JF,JF Fu",
                "luo xiaoping,xiaoping Luo,Luo XP,XP Luo",
                "zhu dalong,daolong Zhu,Zhu DL,DL Zhu",
                "zhao jiajun,jiajun Zhao,Zhao JJ,JJ Zhao",
                "mu yiming,yiming Mu, Mu YM,YM Mu",
                " wang tianyou,tianyou Wang,Wang TY,TY Wang",
                "wang weiqing,weiqing Wang,Wang WQ,WQ Wang",
                "hong tianpei,tianpei Hong,Hong TP,TP Hong",
                "ning guang,guang Ning,Ning G,G Ning",
                " jia weiping,weiping Jia,Jia WP,WP Jia",
                "xiao jianzhong,jianzhong Xiao,Xiao JZ,JZ Xiao",
                "yan li,li Yan,Yan L,L Yan",
                "yan dewen,dewen Yan,Yan DW,DW Yan",
                "bi yan,yan Bi,Bi Y,Y Bi",
                "yang jinkui,jinkui Yang,Yang JK,JK Yang",
                "yang yu,yu yang,Yang Y,Y Yang",
                "yu xuefeng,xuefeng yu,Yu XF,XF Yu",
                "zeng tianshu,tianshu zeng,Zeng TS,TS Zeng",
                "zhang chi,chi zhang,Zhang C,C Zhang",
                "zhang huijie,huijie zhang,Zhang HJ,HJ Zhang",
                "zhang lihui,lihui zhang,Zhang LH,LH Zhang",
                "zhang qiu,qiu zhang,Zhang Q,Q Zhang",
                "zheng chao,chao zheng,Zheng C,C Zheng",
                "zhou jiaqiang,jiaqiang zhou,Zhou JQ,JQ Zhou",
                "zhou jian,jian zhou,Zhou J,J Zhou",
                "cai mengyin,mengyin cai,Cai MY,MY Cai",
                "chen li,li chen,Chen L,L Chen",
                "chen liming,liming chen,Chen LM,LM Chen",
                "chen linqi,linqi chen,Chen LQ,LQ Chen",
                "dong guanping,guanping dong,Dong GP,GP Dong",
                "du jianling,jianling du,Du JL,JL Du",
                "gong chunxiu,chunxiu gong,Gong CX,CX Gong",
                "ji qiuhe,qiuhe ji,Ji QH,QH Ji",
                "jiang hongwei,hongwei jiang,Jiang HW,HW Jiang",
                "jiang sheng,sheng jiang,Jiang S,S Jiang",
                "kuang hongyu,hongyu kuang,Kuang HY,HY Kuang",
                "kuang jian,jian kuang,Kuang J,J Kuang",
                "lei minxiang,minxiang lei,Lei MX,MX Lei",
                "li ling,ling li,Li L,L Li",
                "li pin,pin li,Li P,P Li",
                "li qifu,qifu li,Li QF,QF Li",
                "li xia,xia li,Li X,X Li",
                "li xiaoying,xiaoying li,Li XY,XY Li",
                "li yanbing,yanbing li,Li YB,YB Li",
                "li yiming,yiming li,Li YM,YM Li",
                "su zhe,zhe su,Su Z,Z Su",
                "luo feihong,feihong luo,Luo FH,FH Luo"
        );

        for (String name : names) {
            String[] parts = name.split(",");
//            String strName = String.format("AND ((((%s[Author - First]) OR (%s[Author - First])) OR (%s[Author - First])) OR (%s[Author - First])) AND (y_5[Filter])",
//                    parts[0], parts[1], parts[2], parts[3]);
//            String strName = String.format("AND ((((%s[Author]) OR (%s[Author])) OR (%s[Author])) OR (%s[Author])) AND (y_5[Filter])",
//                    parts[0], parts[1], parts[2], parts[3]);
//            String strName = String.format(" AND ((((%s[Author - Last]) OR (%s[Author - Last])) OR (%s[Author - Last])) OR (%s[Author - Last])) AND (y_5[Filter])",
//                    parts[0], parts[1], parts[2], parts[3]);
//            String strName = String.format("AND ((((%s[Author]) OR (%s[Author])) OR (%s[Author])) OR (%s[Author])) AND (y_5[Filter]) AND (clinicaltrial[Filter])",
//                parts[0], parts[1], parts[2], parts[3]);
//            String  query= "((((((((((((((((((((((((((((((\"Diabetes Mellitus, Type 1\"[Mesh]) OR (Type 1 Diabetes[Title/Abstract])) OR (Diabetes, Type 1[Title/Abstract])) OR (Diabetes Mellitus, Insulin-Dependent[Title/Abstract])) OR (Diabetes Mellitus, Insulin Dependent[Title/Abstract])) OR (Insulin-Dependent Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Juvenile-Onset[Title/Abstract])) OR (Diabetes Mellitus, Juvenile Onset[Title/Abstract])) OR (Juvenile-Onset Diabetes Mellitus[Title/Abstract])) OR (IDDM[Title/Abstract])) OR (Diabetes Mellitus, Type I[Title/Abstract])) OR (Diabetes Mellitus, Sudden-Onset[Title/Abstract])) OR (Diabetes Mellitus, Sudden Onset[Title/Abstract])) OR (Sudden-Onset Diabetes Mellitus[Title/Abstract])) OR (Type 1 Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Insulin-Dependent, 1[Title/Abstract])) OR (Insulin-Dependent Diabetes Mellitus 1[Title/Abstract])) OR (Insulin Dependent Diabetes Mellitus 1[Title/Abstract])) OR (Juvenile-Onset Diabetes[Title/Abstract])) OR (Diabetes, Juvenile-Onset[Title/Abstract])) OR (Juvenile Onset Diabetes[Title/Abstract])) OR (Diabetes, Autoimmune[Title/Abstract])) OR (Autoimmune Diabetes[Title/Abstract])) OR (Diabetes Mellitus, Brittle[Title/Abstract])) OR (Brittle Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Ketosis-Prone[Title/Abstract])) OR (Diabetes Mellitus, Ketosis Prone[Title/Abstract])) OR (Ketosis-Prone Diabetes Mellitus[Title/Abstract]))) OR ((((\"Thyroid Diseases\"[Mesh]) OR (Diseases, Thyroid[Title/Abstract])) OR (Disease, Thyroid[Title/Abstract])) OR (Thyroid Disease[Title/Abstract])))";
//            String  query=" ((((((\"Thyroid Diseases\"[Mesh]) OR (Diseases, Thyroid[Title/Abstract])) OR (Disease, Thyroid[Title/Abstract])) OR (Thyroid Disease[Title/Abstract])) OR (((((((((((((((((((((((((((((\"Diabetes Mellitus, Type 1\"[Mesh]) OR (Type 1 Diabetes[Title/Abstract])) OR (Diabetes, Type 1[Title/Abstract])) OR (Diabetes Mellitus, Insulin-Dependent[Title/Abstract])) OR (Diabetes Mellitus, Insulin Dependent[Title/Abstract])) OR (Insulin-Dependent Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Juvenile-Onset[Title/Abstract])) OR (Diabetes Mellitus, Juvenile Onset[Title/Abstract])) OR (Juvenile-Onset Diabetes Mellitus[Title/Abstract])) OR (IDDM[Title/Abstract])) OR (Diabetes Mellitus, Type I[Title/Abstract])) OR (Diabetes Mellitus, Sudden-Onset[Title/Abstract])) OR (Diabetes Mellitus, Sudden Onset[Title/Abstract])) OR (Sudden-Onset Diabetes Mellitus[Title/Abstract])) OR (Type 1 Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Insulin-Dependent, 1[Title/Abstract])) OR (Insulin-Dependent Diabetes Mellitus 1[Title/Abstract])) OR (Insulin Dependent Diabetes Mellitus 1[Title/Abstract])) OR (Juvenile-Onset Diabetes[Title/Abstract])) OR (Diabetes, Juvenile-Onset[Title/Abstract])) OR (Juvenile Onset Diabetes[Title/Abstract])) OR (Diabetes, Autoimmune[Title/Abstract])) OR (Autoimmune Diabetes[Title/Abstract])) OR (Diabetes Mellitus, Brittle[Title/Abstract])) OR (Brittle Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Ketosis-Prone[Title/Abstract])) OR (Diabetes Mellitus, Ketosis Prone[Title/Abstract])) OR (Ketosis-Prone Diabetes Mellitus[Title/Abstract]))))) ";
//            String  searchTerm = query+strName;
//            String searchTerm = String.format("((((((\"Thyroid Diseases\"[Mesh]) OR (Diseases, Thyroid[Title/Abstract])) OR (Disease, Thyroid[Title/Abstract])) OR (Thyroid Disease[Title/Abstract])) OR (((((((((((((((((((((((((((((\"Diabetes Mellitus, Type 1\"[Mesh]) OR (Type 1 Diabetes[Title/Abstract])) OR (Diabetes, Type 1[Title/Abstract])) OR (Diabetes Mellitus, Insulin-Dependent[Title/Abstract])) OR (Diabetes Mellitus, Insulin Dependent[Title/Abstract])) OR (Insulin-Dependent Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Juvenile-Onset[Title/Abstract])) OR (Diabetes Mellitus, Juvenile Onset[Title/Abstract])) OR (Juvenile-Onset Diabetes Mellitus[Title/Abstract])) OR (IDDM[Title/Abstract])) OR (Diabetes Mellitus, Type I[Title/Abstract])) OR (Diabetes Mellitus, Sudden-Onset[Title/Abstract])) OR (Diabetes Mellitus, Sudden Onset[Title/Abstract])) OR (Sudden-Onset Diabetes Mellitus[Title/Abstract])) OR (Type 1 Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Insulin-Dependent, 1[Title/Abstract])) OR (Insulin-Dependent Diabetes Mellitus 1[Title/Abstract])) OR (Insulin Dependent Diabetes Mellitus 1[Title/Abstract])) OR (Juvenile-Onset Diabetes[Title/Abstract])) OR (Diabetes, Juvenile-Onset[Title/Abstract])) OR (Juvenile Onset Diabetes[Title/Abstract])) OR (Diabetes, Autoimmune[Title/Abstract])) OR (Autoimmune Diabetes[Title/Abstract])) OR (Diabetes Mellitus, Brittle[Title/Abstract])) OR (Brittle Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Ketosis-Prone[Title/Abstract])) OR (Diabetes Mellitus, Ketosis Prone[Title/Abstract])) OR (Ketosis-Prone Diabetes Mellitus[Title/Abstract]))))) AND ((((%s[Author - First]) AND (%s[Author - First])) AND (%s[Author - First])) AND (%s[Author - First])) AND (y_5[Filter])",
//                    parts[0], parts[1], parts[2], parts[3]);
            String searchTerm = String.format("(((((\"Thyroid Diseases\"[Mesh]) OR (Diseases, Thyroid[Title/Abstract])) OR (Disease, Thyroid[Title/Abstract])) OR (Thyroid Disease[Title/Abstract])) OR (((((((((((((((((((((((((((\"Diabetes Mellitus, Type 1\"[Mesh]) OR (Type 1 Diabetes[Title/Abstract])) OR (Diabetes, Type 1[Title/Abstract])) OR (Diabetes Mellitus, Insulin-Dependent[Title/Abstract])) OR (Diabetes Mellitus, Insulin Dependent[Title/Abstract])) OR (Insulin-Dependent Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Juvenile-Onset[Title/Abstract])) OR (Diabetes Mellitus, Juvenile Onset[Title/Abstract])) OR (Juvenile-Onset Diabetes Mellitus[Title/Abstract])) OR (IDDM[Title/Abstract])) OR (Diabetes Mellitus, Type I[Title/Abstract])) OR (Diabetes Mellitus, Sudden-Onset[Title/Abstract])) OR (Diabetes Mellitus, Sudden Onset[Title/Abstract])) OR (Sudden-Onset Diabetes Mellitus[Title/Abstract])) OR (Type 1 Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Insulin-Dependent, 1[Title/Abstract])) OR ((Insulin-Dependent Diabetes Mellitus 1[Title/Abstract])) OR (Insulin Dependent Diabetes Mellitus 1[Title/Abstract])) OR (Juvenile-Onset Diabetes[Title/Abstract])) OR (Diabetes, Juvenile-Onset[Title/Abstract])) OR (Juvenile Onset Diabetes[Title/Abstract])) OR (Diabetes, Autoimmune[Title/Abstract])) OR (Autoimmune Diabetes[Title/Abstract])) OR (Diabetes Mellitus, Brittle[Title/Abstract])) OR (Brittle Diabetes Mellitus[Title/Abstract])) OR (Diabetes Mellitus, Ketosis-Prone[Title/Abstract])) OR (Diabetes Mellitus, Ketosis Prone[Title/Abstract])) OR (Diabetes Mellitus, Ketosis Prone[Title/Abstract]))) AND ((((\"%s\"[Author - First]) OR (\"%s\"[Author - First])) OR (\"%s\"[Author - First])) OR (\"%s\"[Author - First]))  AND (y_5[Filter]) ",
                    parts[0], parts[1], parts[2], parts[3]);

            System.out.println("name: " + parts[0]);
            System.out.println("查询字符串: " + searchTerm);
            System.out.println();
            String apiUrl = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi";
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                // 第一步：搜索文献获取PMID列表（支持翻页）
                int retstart = 0;
                int retmax = 100; // 每页返回的最大记录数
                boolean hasMoreResults = true;
                List<String> allPmids = new ArrayList<>();
                JsonNode idListNode = null;
                while (hasMoreResults) {
                    String searchUrl = String.format("%s?db=pubmed&term=%s&retmode=json&retstart=%d&retmax=%d",
                            apiUrl,
                            java.net.URLEncoder.encode(searchTerm, "UTF-8"),
                            retstart,
                            retmax);

                    HttpGet searchRequest = new HttpGet(searchUrl);

                    try (CloseableHttpResponse searchResponse = httpClient.execute(searchRequest)) {
                        HttpEntity searchEntity = searchResponse.getEntity();

                        if (searchEntity != null) {
                            String searchResult = EntityUtils.toString(searchEntity);
                            ObjectMapper mapper = new ObjectMapper();
                            JsonNode rootNode = mapper.readTree(searchResult);

                            // 提取PMID列表
                            idListNode = rootNode.path("esearchresult").path("idlist");
                            if (idListNode.isArray() && idListNode.size() > 0) {
                                for (JsonNode idNode : idListNode) {
                                    String pmid = idNode.asText();
                                    allPmids.add(pmid);
                                }
                                retstart += retmax; // 更新起始位置
                            } else {
                                hasMoreResults = false; // 没有更多结果，退出循环
                            }
                        }
                    }
                }

                if (!allPmids.isEmpty()) {
                    System.out.println("找到的文献PMID列表:");
                    for (String pmid : allPmids) {
                        System.out.println("PMID: " + pmid);
                    }
                    System.out.println("共找到 " + allPmids.size() + " 篇文献");
                } else {
                    System.out.println("未找到匹配的文献");
                }
                // 第4步：将查询结果保存到本地文件
                String outputFile = "query_results_first.txt";
                try (PrintWriter writer = new PrintWriter(new FileWriter(outputFile, true))) {
                    writer.println("姓名: " + name);
                    writer.println("查询字符串: " + searchTerm);
                    writer.println("PMID列表: " + allPmids.toString());
                    writer.println("合计: " + allPmids.size());
                    writer.println("----------------------------------");
                } catch (IOException e) {
                    System.err.println("保存文件时出错: " + e.getMessage());
                }

            }catch(IOException e) {
                System.err.println("网络请求时出错: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}

